package com.openthinks.joyniproject.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.openthinks.joyniproject.model.UserInfo;
import com.openthinks.joyniproject.service.AccountService;
import com.openthinks.joyniproject.utils.Constants;
import com.openthinks.joyniproject.utils.Encrypter;

@Controller
public class AccountController {

private static Logger logger = Logger.getLogger(AccountController.class);
	
	@Autowired
	private AccountService accountService;
	
    @RequestMapping(value="/account/login",method=RequestMethod.POST)
    @ResponseBody
	public Map<String,Object> login(UserInfo loginUser,HttpServletRequest request,HttpServletResponse response){
    	
        Map<String,Object> result = new HashMap<String,Object>();
        
		try {
			loginUser.setPassword(Encrypter.md5s(loginUser.getPassword()));
			UserInfo userInfo = this.accountService.getUserInfo(loginUser);
			
			if(userInfo!=null){
				request.getSession().setAttribute("userInfo", userInfo);
				result.put("redirectURL", Constants.SYSTEM_PATH+"/main");
				result.put("result", Constants.RESULT_FLAG_SUCCESS);
			}else{
				result.put("result", Constants.RESULT_FLAG_FAILURE);
			}
		} catch (Exception e) {
			logger.error("account login error...",e);
            result.put("result", Constants.RESULT_FLAG_FAILURE);
		}
        return result;
	}
    
    @RequestMapping(value="/main")
   	public String index(){
       	String redirectUrl = "/index.html";
    return redirectUrl;
    }
    
   
    @RequestMapping(value="/account/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	   
	       request.getSession().invalidate();//session失效
	       return "redirect:/index.html";
	}
}
